package com.dxg.msns.music.service.impl;

import com.dxg.msns.common.pojo.PageResult;
import com.dxg.msns.common.util.UnderlineHump;
import com.dxg.msns.music.client.UserClient;
import com.dxg.msns.music.mapper.MusicFavorMapper;
import com.dxg.msns.music.mapper.MusicGradeMapper;
import com.dxg.msns.music.mapper.MusicMapper;
import com.dxg.msns.music.mapper.PlaylistMapper;
import com.dxg.msns.music.pojo.*;
import com.dxg.msns.music.service.MusicService;

import com.dxg.msns.user.pojo.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class MusicServiceImpl implements MusicService {
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private PlaylistMapper playlistMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private UserClient userClient;
    @Autowired
    private MusicFavorMapper musicFavorMapper;



    @Autowired
    private MusicGradeMapper musicGradeMapper;

    private void sendMsg(Integer id,String type) {
        //向队列发送消息
        try {
            this.amqpTemplate.convertAndSend("music."+type, id.toString());
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }
    @Override
    public PageResult<Music> queryMusicsByPage(String key, Integer page, Integer rows, String[] sortBy, Boolean[] desc) {
        Example example = new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("musicName", "%" + key + "%");
        }
        //添加分页条件
        PageHelper.startPage(page, rows);

        //添加排序条件
        if (ArrayUtils.isNotEmpty(sortBy)) {
            example.setOrderByClause(UnderlineHump.HumpToUnderline(sortBy[0]) + " " + (desc[0] ? "desc" : "asc"));
        }
        List<Music> musics = this.musicMapper.selectByExample(example);
        PageInfo<Music> musicPageInfo = new PageInfo<>(musics);

        return new PageResult<>(musicPageInfo.getTotal(), musicPageInfo.getList());
    }

    /**
     * 查询音乐分类统计
     *
     * @return
     */
    @Override
    public List<TypeStatistics> queryTypeStatistics() {
        return this.musicMapper.queryTypeStatistics();
    }

    /**
     * 修改音乐
     *
     * @param music
     */
    @Override
    @Transactional
    public void updateMusic(Music music) {
        Example example = new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", music.getId());
        this.musicMapper.updateByExampleSelective(music, example);
        sendMsg(music.getId(),"update");

    }

    /**
     * 添加音乐
     * @param music
     */
    @Override
    @Transactional
    public void saveMusic(Music music) {
        music.setMusicId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
        Date date = new Date();
        music.setMusicPushDate(date);

        this.musicMapper.insertSelective(music);
        sendMsg(music.getId(),"insert");
    }

    /**
     * 查找是否有相同音乐
     *
     * @param music
     * @return
     */
    @Override
    public boolean findMusicByInfo(Music music) {
        Example example = new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("musicName",music.getMusicName()).andEqualTo("musicAuthor",music.getMusicAuthor()).andEqualTo("musicAlbum",music.getMusicAlbum());
        List<Music> musicList = this.musicMapper.selectByExample(example);
        System.out.println(musicList);
        if (musicList.size() > 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 删除音乐
     *
     * @param music
     */
    @Override
    @Transactional
    public void deleteMusic(Music music) {
        Example example = new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",music.getId());
        this.musicMapper.deleteByExample(example);
        sendMsg(music.getId(),"delete");
    }

    /**
     * 根据id查找音乐
     *
     * @param id
     * @return
     */
    @Override
    public Music queryMusicById(Integer id) {
        return  this.musicMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据音乐id查找音乐
     *
     * @param musicId
     * @return
     */
    @Override
    public Music queryMusicByMusicId(String musicId) {
        Music music = new Music();
        music.setMusicId(musicId);
        return  this.musicMapper.selectOne(music);
    }

    @Override
    public List<Music> queryMusicAll() {
        // 返回所有状态不为 0（即未删除）的音乐记录
        Example example = new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", "0");
        return this.musicMapper.selectByExample(example);
    }

    @Override
    public PageResult<MusicVo> queryMusicOrder(String uid, Integer page, Integer rows) {
        try {
            // 参数验证
            if (org.springframework.util.StringUtils.isEmpty(uid)) {
                return new PageResult<>(0L, null);
            }

            if (page == null || page < 1) {
                page = 1;
            }
            if (rows == null || rows < 1) {
                rows = 10;
            }

            // 1. 查询所有状态不为0的音乐（即未删除）
            Example example = new Example(Music.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andNotEqualTo("status", "0");

            // 按照 music_average_grade 转为数字降序排序
            example.setOrderByClause("CAST(music_average_grade AS UNSIGNED) DESC");

            // 查询排序后的全部音乐列表（未分页）
            List<Music> allMusicList = musicMapper.selectByExample(example);
            long total = allMusicList.size(); // 总记录数

            // 分页处理（手动分页）
            int fromIndex = (page - 1) * rows;
            int toIndex = Math.min(fromIndex + rows, allMusicList.size());
            if (fromIndex >= total) {
                return new PageResult<>(total, new ArrayList<>());
            }
            List<Music> pagedMusicList = allMusicList.subList(fromIndex, toIndex);

            // 查询该用户收藏的音乐 ID 列表
            List<String> favorMusicIds = musicFavorMapper.queryByUid(uid);
            Set<String> favorSet = new HashSet<>(favorMusicIds);

            // 封装为 MusicVo 列表
            List<MusicVo> result = new ArrayList<>();
            for (Music music : pagedMusicList) {
                int favorStatus = favorSet.contains(music.getId().toString()) ? 1 : 0;
                MusicVo musicVo = new MusicVo(music, favorStatus);
                result.add(musicVo);
            }

            // 返回分页结果
            return new PageResult<>(total, result);

        } catch (Exception e) {
            System.err.println("查询音乐排序时出现异常：" + e.getMessage());
            e.printStackTrace();
            return new PageResult<>(0L, new ArrayList<>());
        }
    }


    /**
     * 根据歌手名称查询歌曲信息，且排除状态为 0的歌曲
     *
     * @param singerName 歌手名称
     * @return 歌曲列表
     */
    @Override
    public List<Music> queryMusicBySinger(String singerName) {
        Example example = new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("musicAuthor", singerName); // 根据歌手名称查询
        criteria.andNotEqualTo("status", "0"); // 排除 status 为 0的歌曲
        return musicMapper.selectByExample(example);
    }

    /**
     * 根据歌曲名称查询歌曲信息，且排除状态为 0的歌曲
     *
     * @param musicName 歌曲名称
     * @return 歌曲列表
     */
    @Override
    public List<Music> queryMusicByMusicName(String musicName) {
        Example example = new Example(Music.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("musicName", musicName); // 根据歌曲名称查询
        criteria.andNotEqualTo("status", "0"); // 排除 status 为 -1 的歌曲
        return musicMapper.selectByExample(example);
    }

    @Override
    public Integer addMusic(Music music) {
        try {
            // 手动设置 musicId（生成一个 UUID 作为 musicId）
            String musicId = UUID.randomUUID().toString().replace("-", "").toLowerCase(); // 生成唯一的 musicId
            music.setMusicId(musicId);  // 设置 musicId

            music.setStatus("1");  // 设置 status 为 1

            // 设置上传时间
            Date date = new Date();
            music.setMusicPushDate(date); // 设置上传时间

            // 保存音乐到数据库
            Integer row = this.musicMapper.insertSelective(music);
            return row;  // 返回插入影响的行数
        } catch (Exception e) {
            e.printStackTrace();  // 打印异常堆栈信息
            return 0;  // 出现异常时返回 0
        }
    }

    @Override
    public Integer underMusic(String musicId) {
        try {
            // 执行更新操作
            Integer rowsAffected = this.musicMapper.updateStatusByMusicId(musicId);

            // 如果更新的行数大于 0，说明成功，否则返回 -1
            if (rowsAffected > 0) {
                return rowsAffected;  // 返回更新成功的行数
            } else {
                return -1;  // 如果没有更新任何行，返回-1
            }
        } catch (Exception e) {
            System.out.println(e);
            return -1;  // 捕获异常时返回-1
        }
    }

    @Override
    public String markMusic(String userId, String musicId, String mark) {
        int averageGrade = 0;  // 提前声明并初始化 averageGrade 变量

        try {
            // 1. 确保用户没有重复评分
            List<MusicGrade> existingGrades = musicGradeMapper.selectByUserAndMusicId(userId, musicId);
            if (existingGrades != null && !existingGrades.isEmpty()) {
                return "用户已评分";  // 如果用户已经评分，则直接返回
            }

            // 2. 插入评分记录到 music_grade 表
            MusicGrade musicGrade = new MusicGrade();
            musicGrade.setMusicId(musicId);
            musicGrade.setUserId(userId);
            musicGrade.setMusicGrade(Integer.parseInt(mark));  // 将评分转换为整数
            musicGrade.setCreatTime(new Date());  // 设置创建时间
            musicGrade.setStatus(1);  // 设置评分状态为有效 (1)

            // 保存评分记录
            musicGradeMapper.insertSelective(musicGrade);


            // 3. 查询该音乐的所有评分记录并计算平均评分
            List<MusicGrade> grades = musicGradeMapper.selectByMusicIds(musicId);
            System.out.println("打分列表"+grades);
            if (grades != null && !grades.isEmpty()) {
                int totalGrade = 0;
                int count = 0;
                for (MusicGrade grade : grades) {
                    if (grade != null && grade.getMusicGrade() != null) {  // 增加空检查
                        totalGrade += grade.getMusicGrade();
                        count++;
                        System.out.println("进循环里了嘎嘎嘎嘎嘎嘎嘎嘎嘎嘎嘎嘎嘎");
                    }
                }
                System.out.println("1111111111111111111"+count);
                System.out.println("2222222222222222222"+totalGrade);
                // 计算平均分
                if (count > 0) {
                    averageGrade = totalGrade / count;  // 计算平均分

                    System.out.println("333333333333333"+averageGrade);
                }
            }

            // 4. 将平均分转换为 String 类型
            String averageGradeStr = String.valueOf(averageGrade);

            // 5. 更新 music 表中的 music_average_grade
            Music music = new Music();
            music.setMusicId(musicId);
            music.setMusicAverageGrade(averageGradeStr);  // 设置更新后的平均评分 (作为 String)
            // 调用 MusicMapper 的方法来更新数据库
            musicMapper.updateAverageGradeByMusicId(music.getMusicId(), music.getMusicAverageGrade());
            // 6. 返回更新后的平均评分（String 类型）
            return averageGradeStr;

        } catch (Exception e) {
            e.printStackTrace();
            return "评分失败";
        }
    }


    @Override
    public PageResult<Search> queryMusicByAll(String searchInfo, Integer type, String uid, Integer page, Integer rows) {
        // 初始化分页参数
        if (page == null || page < 1) page = 1;
        if (rows == null || rows < 1) rows = 10;

        List<MusicVo> musicVoList = new ArrayList<>();
        List<Playlist> playlistList = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        long total = 0;  // 总条数

        try {
            // ============ 查询歌曲 ============
            if (type == null || type == 1) {
                List<Music> allMusic = musicMapper.queryMusicByMusicName(searchInfo);
                if (allMusic == null) allMusic = new ArrayList<>();

                // 获取用户收藏的音乐 ID 列表
                List<String> favorIds = musicFavorMapper.queryByUid(uid);
                Set<String> favorSet = new HashSet<>(favorIds);

                // 手动分页
                total = allMusic.size();
                int fromIndex = (page - 1) * rows;
                int toIndex = Math.min(fromIndex + rows, allMusic.size());
                if (fromIndex < total) {
                    List<Music> pageMusicList = allMusic.subList(fromIndex, toIndex);
                    for (Music music : pageMusicList) {
                        int favorStatus = favorSet.contains(music.getId().toString()) ? 1 : 0;
                        musicVoList.add(new MusicVo(music, favorStatus));
                    }
                }
            }

            // ============ 查询歌单 ============
            if (type == null || type == 2) {
                playlistList = playlistMapper.selectPlaylistsBySearch(searchInfo);
                if (playlistList == null) playlistList = new ArrayList<>();

                if (type != null && type == 2) {
                    total = playlistList.size();
                    // 分页
                    int fromIndex = (page - 1) * rows;
                    int toIndex = Math.min(fromIndex + rows, playlistList.size());
                    if (fromIndex < total) {
                        playlistList = playlistList.subList(fromIndex, toIndex);
                    } else {
                        playlistList = new ArrayList<>();
                    }
                }
            }

            // ============ 查询用户 ============
            if (type == null || type == 3) {
                userList = userClient.queryUsersByName(searchInfo);
                if (userList == null) userList = new ArrayList<>();

                if (type != null && type == 3) {
                    total = userList.size();
                    int fromIndex = (page - 1) * rows;
                    int toIndex = Math.min(fromIndex + rows, userList.size());
                    if (fromIndex < total) {
                        userList = userList.subList(fromIndex, toIndex);
                    } else {
                        userList = new ArrayList<>();
                    }
                }
            }

        } catch (Exception e) {
            System.err.println("搜索查询失败：" + e.getMessage());
            e.printStackTrace();
            return new PageResult<>(0L, new ArrayList<>());
        }

        // 组装返回对象
        Search result = new Search();
        result.setMusicListVoList(musicVoList);
        result.setPlaylist(playlistList);
        result.setUserInfoList(userList);

        // 构建分页返回结果
        List<Search> resultList = new ArrayList<>();
        resultList.add(result);

        return new PageResult<>(total, resultList);
    }



}
